<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>{{ isRegister ? '注册新账号' : '欢迎登录外卖平台' }}</h2>
      </div>

      <div class="login-logo">
        <img src="@/assets/logo.png" alt="外卖平台" />
      </div>

      <el-form
        :model="form"
        @submit.prevent="handleSubmit"
        class="login-form"
      >
        <!-- 手机号输入 -->
        <el-form-item prop="phone" :rules="phoneRules">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号"
            prefix-icon="el-icon-mobile-phone"
            clearable
          />
        </el-form-item>

        <!-- 注册时需要用户名 -->
        <el-form-item v-if="isRegister" prop="username" :rules="usernameRules">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
            clearable
          />
        </el-form-item>

        <!-- 密码输入 (登录和注册都需要) -->
        <el-form-item v-if="!isVerificationLogin || isRegister" prop="password" :rules="passwordRules">
          <el-input
            v-model="form.password"
            type="password"
            :placeholder="isRegister ? '请设置密码' : '默认密码111111'"
            prefix-icon="el-icon-lock"
            show-password
            clearable
          />
        </el-form-item>

        <!-- 验证码登录/注册表单 -->
        <template v-if="isVerificationLogin">
          <el-form-item prop="verificationCode" :rules="verificationCodeRules">
            <div class="verification-code-input">
              <el-input
                v-model="form.verificationCode"
                placeholder="请输入验证码"
                prefix-icon="el-icon-message"
                clearable
              />
              <el-button
                class="get-code-btn"
                :disabled="countdown > 0 || !locationReady"
                @click="sendVerificationCode"
              >
                {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>

          <div class="login-tips" v-if="!isRegister">
            新用户第一次使用验证码登录将自动注册
          </div>
        </template>

        <!-- 位置信息展示 -->
        <div v-if="locationLoading" class="location-loading">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>正在获取当前位置...</span>
        </div>
        <div v-else-if="locationError" class="location-error">
          <el-icon><Warning /></el-icon>
          <span>{{ locationError }}</span>
          <el-button type="text" @click="retryGetLocation">重试</el-button>
        </div>
        <div v-else class="current-location">
          <el-icon><Location /></el-icon>
          <span>{{ currentAddress }}</span>
        </div>

        <div class="login-actions">
          <el-button
            type="primary"
            native-type="submit"
            class="login-btn"
            :loading="loading"
            :disabled="!locationReady"
          >
            {{ isRegister ? '注册' : '登录' }}
          </el-button>

          <div class="switch-actions">
            <div class="switch-login-type" @click="switchLoginType" v-if="!isRegister">
              {{ isVerificationLogin ? '使用密码登录' : '使用验证码登录' }}
            </div>
            <div class="switch-register" @click="isRegister = !isRegister">
              {{ isRegister ? '已有账号？去登录' : '没有账号？去注册' }}
            </div>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { API_BASE_URL } from '@/config';
import { useCookies } from 'vue3-cookies';
import { ElMessage } from 'element-plus';
import { ElementPlus, Loading, Location, Warning } from '@element-plus/icons-vue';

const { cookies } = useCookies();
const router = useRouter();

// 表单数据
const form = reactive({
  phone: '',
  username: '',
  password: '',
  verificationCode: '',
  nowaddress: ''
});

const loginType = ref('password'); // 'password' 或 'verification'
const isRegister = ref(false);
const countdown = ref(0);
const loading = ref(false);
const locationReady = ref(false);
const locationLoading = ref(true);
const locationError = ref('');
const currentAddress = ref('');
const userrespnse = ref([]);
// 计算属性
const isVerificationLogin = computed(() => {
  return !isRegister.value && loginType.value === 'verification';
});

// 表单验证规则
const phoneRules = [
  { required: true, message: '请输入手机号', trigger: 'blur' },
  { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
];

const usernameRules = [
  { required: true, message: '请输入用户名', trigger: 'blur' },
  { min: 2, max: 20, message: '用户名长度在2到20个字符', trigger: 'blur' }
];

const passwordRules = [
  { required: true, message: '请输入密码', trigger: 'blur' },
  { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
];

const verificationCodeRules = [
  { required: true, message: '请输入验证码', trigger: 'blur' },
  { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
];

// 组件挂载时获取位置
onMounted(() => {
  getLocation();
});

// 获取地理位置功能（使用浏览器API）
const getLocation = () => {
  locationLoading.value = true;
  locationError.value = '';
  locationReady.value = false;

  return new Promise((resolve, reject) => {
    if (!navigator.geolocation) {
      reject(new Error('您的浏览器不支持地理位置服务'));
      return;
    }

    navigator.geolocation.getCurrentPosition(
      position => {
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;
        cookies.set("latitude",latitude)
        cookies.set("longitude",longitude)
        console.log("latitude:"+latitude+"longitude:"+longitude)
        resolve({ latitude, longitude });
      },
      error => {
        let errorMessage = '';
        switch (error.code) {
          case error.PERMISSION_DENIED:
            errorMessage = '您拒绝了位置访问权限';
            break;
          case error.POSITION_UNAVAILABLE:
            errorMessage = '无法获取当前位置，请检查您的网络连接或设备设置';
            break;
          case error.TIMEOUT:
            errorMessage = '获取位置超时，请稍后再试';
            break;
          default:
            errorMessage = '未知错误';
        }
        reject(new Error(errorMessage));
      }
    );
  }).then(async location => {
    try {
      const addressInfo = await getAddressByLatLng(location.latitude, location.longitude);

      return { ...location, address: addressInfo };
    } catch (error) {
      throw new Error('无法获取地址信息: ' + error.message);
    }
  }).then(locationWithAddress => {
    currentAddress.value = locationWithAddress.address;
    form.nowaddress = locationWithAddress.address;
    locationReady.value = true;
    locationLoading.value = false;
  }).catch(error => {
    locationError.value = error.message;
    locationLoading.value = false;
    // 使用默认地址
    form.nowaddress = '北京市朝阳区';
    currentAddress.value = '北京市朝阳区';
    locationReady.value = true;
  });

};

// 根据经纬度获取地址信息（使用高德地图逆地址编码API）
const getAddressByLatLng = async (latitude, longitude) => {
  // 1. 首先尝试从cookie获取地址
  const savedAddress = cookies.get('address');
  if (savedAddress) {
    return savedAddress;
  }

  // 2. 如果没有保存的地址，则调用高德API
  const amapKey = 'b6a7d20b6ae2ec5c6dc4580a3cd329bc';
  const url = `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${longitude},${latitude}&key=${amapKey}`;

  try {
    const response = await axios.get(url);
    if (response.data.status === '1' && response.data.regeocode.formatted_address) {
      const address = response.data.regeocode.formatted_address;
      // 将获取到的地址存入cookie，有效期1天
      cookies.set('address', address, 60 * 60 * 24 * 1);
      return address;
    } else {
      throw new Error(response.data.info || '无法获取地址信息');
    }
  } catch (error) {
    console.error('高德API调用失败:', error);
    // 如果API调用失败，使用默认地址并存入cookie
    const defaultAddress = '北京市朝阳区';
    cookies.set('address', defaultAddress, 60 * 60 * 24 * 7);
    return defaultAddress;
  }
};

// 重试获取位置
const retryGetLocation = () => {
  getLocation();
};

// 切换登录方式
const switchLoginType = () => {
  loginType.value = loginType.value === 'password' ? 'verification' : 'password';
};

// 发送验证码
const sendVerificationCode = async () => {
  if (!form.phone || !/^1[3-9]\d{9}$/.test(form.phone)) {
    ElMessage.error('请输入正确的手机号');
    return;
  }

  try {
    const response = await axios.post(`${API_BASE_URL}/getsms`, null, {
      params: {
        phone_number: form.phone,
        nowaddress: form.nowaddress
      }
    });

    if (response.status === 200) {
      ElMessage.success('验证码发送成功');
      startCountdown();
    } else {
      ElMessage.error('验证码发送失败');
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '验证码发送失败');
  }
};

// 倒计时
const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// 处理表单提交
const handleSubmit = async () => {
  if (!locationReady.value) {
    ElMessage.warning('正在获取位置信息，请稍后');
    return;
  }

  if (isRegister.value) {
    await handleRegister();
  } else if (loginType.value === 'password') {
    await handlePasswordLogin();
  } else {
    await handleVerificationCodeLogin();
  }
};

// 注册处理
const handleRegister = async () => {
  loading.value = true;
  try {
    const response = await axios.post(`${API_BASE_URL}/user/register`, null, {
      params: {
        phone: form.phone,
        password: form.password,
        username: form.username
        // 注册接口不需要位置信息
      }
    });

    if (response.status === 201) {
      ElMessage.success('注册成功');
      // 注册成功后自动切换到密码登录
      isRegister.value = false;
      loginType.value = 'password';
    } else {
      ElMessage.error('注册失败');
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '注册失败');
  } finally {
    loading.value = false;
  }
};

// 密码登录
const handlePasswordLogin = async () => {
  loading.value = true;
  try {
    const response = await axios.post(`${API_BASE_URL}/user/loginbypassword`, null, {
      params: {
        phone: form.phone,
        password: form.password,
        nowaddress: form.nowaddress
      }
    });

    handleLoginSuccess(response);
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '登录失败');
  } finally {
    loading.value = false;
  }
};

// 验证码登录
const handleVerificationCodeLogin = async () => {
  loading.value = true;
  try {
    const response = await axios.post(`${API_BASE_URL}/user/loginbyphone`, null, {
      params: {
        phone: form.phone,
        verification_code: form.verificationCode,
        nowaddress: form.nowaddress
      }
    });

    handleLoginSuccess(response);
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '登录失败');
  } finally {
    loading.value = false;
  }
};

// 登录成功处理
const handleLoginSuccess = (response) => {

  if (response.status === 200) {
    // 从响应头获取Authorization token
    const authHeader = response.headers['authorization'];
    const token = authHeader ? authHeader.replace('Bearer ', '') : null;
    // 获取响应体中的用户ID
    userrespnse.value=response.data;

    if (token && userrespnse.value.userId) {

      // 存储token、用户ID和手机号到cookie，设置7天有效期
      cookies.set('usertoken', token, 60 * 60 * 24 * 1);
      cookies.set('userId', userrespnse.value.userId, 60 * 60 * 24 * 1);
      cookies.set('username',userrespnse.value.username,60*60*24*1)
      cookies.set('phone', form.phone, 60 * 60 * 24 * 1);
      cookies.set('address', form.nowaddress, 60 * 60 * 24 * 1);

      ElMessage.success('登录成功');
      router.push('/Msite');
    } else {
      ElMessage.error('登录信息不完整');
    }
  } else {
    ElMessage.error('登录失败，请重试');
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  background-image: linear-gradient(120deg, #f6d365 0%, #fda085 100%);
}

.login-box {
  width: 400px;
  padding: 40px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  font-size: 24px;
}

.login-logo {
  text-align: center;
  margin-bottom: 30px;
}

.login-logo img {
  width: 120px;
  height: 120px;
  object-fit: contain;
}

.login-form {
  margin-top: 20px;
}

.login-actions {
  margin-top: 30px;
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
}

.switch-actions {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
}

.switch-login-type,
.switch-register {
  color: #409eff;
  cursor: pointer;
  font-size: 14px;
}

.switch-login-type:hover,
.switch-register:hover {
  text-decoration: underline;
}

.verification-code-input {
  display: flex;
  gap: 10px;
}

.get-code-btn {
  width: 120px;
}

.login-tips {
  margin-top: -10px;
  margin-bottom: 20px;
  font-size: 12px;
  color: #999;
  text-align: center;
}

.location-loading,
.location-error,
.current-location {
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #666;
  gap: 5px;
}

.location-loading .el-icon {
  margin-right: 5px;
  animation: rotating 2s linear infinite;
}

.location-error .el-icon {
  color: #f56c6c;
}

.current-location .el-icon {
  color: #409eff;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
